<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-button type="primary" @click="getObtain" v-if="formType === 'create'">{{
      t('common.ObtainEISC')
    }}</el-button>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
      style="margin-top: 10px"
    >
      <el-row :gutter="20">
        <!--左侧块------------------------------------------------------------->
        <el-col :span="12">
          <el-form-item :label="t('formData.wellName')" prop="wellName">
            <el-input
              v-model="formData.wellName"
              :placeholder="t('formData.wellNameInput')"
              :disabled="
                clicks && ESICValue.wellName !== null && ESICValue.wellName !== undefined
                  ? true
                  : false
              "
            />
          </el-form-item>

          <el-form-item :label="t('formData.wellCategory')" prop="wellCategory">
            <el-select
              v-model="formData.wellCategory"
              :placeholder="t('formData.wellCategoryInfo')"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.WELL_CATEGORY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="t('formData.oilFieldBlock')" prop="oilFieldBlock">
            <el-select
              v-model="formData.oilFieldBlock"
              :placeholder="t('formData.oilFieldBlockInfo')"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BLOCK)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <!--          <el-form-item :label="t('formData.Longitude')" prop="longitude">
            <el-input v-model="formData.longitude" :placeholder="t('formData.LongitudeInfo')" />
          </el-form-item>-->

          <el-form-item :label="t('formData.drillingDate')" prop="drillingDate">
            <el-date-picker
              v-model="formData.drillingDate"
              type="date"
              :placeholder="t('formData.drillingDateInfo')"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item :label="t('formData.contactPerson')" prop="contactPerson">
            <el-input
              v-model="formData.contactPerson"
              :placeholder="t('formData.contactPersonInfo')"
            />
          </el-form-item>
        </el-col>
        <!--右侧块------------------------------------------------------------->
        <el-col :span="12">
          <!--          <el-form-item :label="t('formData.wellId')" prop="wellId">
            <el-select v-model="formData.wellId" :placeholder="t('formData.wellIdInfo')">
              <el-option
                v-for="dict in getStrDictOptions()"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>-->

          <el-form-item :label="t('formData.wellType')" prop="wellType">
            <el-select v-model="formData.wellType" :placeholder="t('formData.wellTypeInfo')">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.WELL_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item :label="t('formData.oilField')" prop="oilField">
            <el-input v-model="formData.oilField" :placeholder="t('formData.oilFieldInfo')" />
          </el-form-item>

          <el-form-item :label="t('formItems.location')" prop="addressId">
            <el-cascader
              v-model="selectedAddress"
              :options="addressDataTree"
              clearable
              @change="addressChanges"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              :placeholder="t('formItems.locationPlaceholder')"
            />
          </el-form-item>

          <!--          <el-form-item :label="t('formData.Latitude')" prop="latitude">
            <el-input v-model="formData.latitude" :placeholder="t('formData.LatitudeInfo')" />
          </el-form-item>-->

          <el-form-item :label="t('formData.designWellde')" prop="designWellde">
            <el-input
              v-model="formData.designWellde"
              :placeholder="t('formData.designWelldeInfo')"
            />
          </el-form-item>

          <el-form-item :label="t('formData.contactPhone')" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              :placeholder="t('formData.contactPhoneInfo')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="t('formData.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="4"
          :placeholder="t('formData.remarkInfo')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('action.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('action.cancel') }}
      </el-button>
    </template>
  </Dialog>
  <Dialog
    :title="t('common.ObtainEISC')"
    v-model="dialogVisibleable"
    width="1500px"
    style="height: 800px"
    @close="handleDialogClose"
  >
    <el-table
      :data="datas"
      @current-change="handleCurrentChange"
      :show-overflow-tooltip="true"
      style="height: 640px; margin-bottom: 10px"
      v-loading="loading"
    >
      <el-table-column :label="t('formData.wellName')" prop="wellName" align="center" />
      <el-table-column :label="t('formData.wellType')" prop="wellTypeName" align="center" />
      <el-table-column :label="t('formData.oilField')" prop="oilFieldName" align="center" />
      <el-table-column :label="t('formData.drillingDate')" prop="createDateShow" align="center" />
      <el-table-column :label="t('formData.contactPerson')" prop="userName" align="center" />
      <el-table-column :label="t('formData.wellId')" prop="wellId" align="center" />
      <el-table-column :label="t('formData.wellCategory')" prop="wellSortName" align="center" />
      <el-table-column
        :label="t('formData.oilFieldBlock')"
        prop="oilFieldBlockName"
        align="center"
      />
      <!-- <el-table-column :label="t('formData.designWellde')" prop="designWellde" align="center" /> -->
      <!-- <el-table-column :label="t('formData.contactPhone')" prop="contactPhone" align="center" /> -->
      <el-table-column :label="t('formData.location')" align="center">
        <template #default="scope"
          >{{ scope.row.countryName }}{{ scope.row.provinceName }}{{ scope.row.cityName }}
        </template>
      </el-table-column>
      <el-table-column :label="t('formData.remark')" prop="remark" align="center" />
    </el-table>
    <Pagination
      :total="total"
      v-model:page="query.pageNum"
      v-model:limit="query.pageSize"
      @pagination="getTable"
    />
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { SiteApi, SiteVO } from '@/api/base/site'
import { defaultProps } from '@/utils/tree'
import { reactive } from 'vue'
import { ElMessage } from 'element-plus'

/** 现场 表单 */
defineOptions({ name: 'SiteForm' })
const loading = ref(true) // 列表的加载中

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const clicks = ref(false)
const dialogVisibleable = ref(false) // 弹窗的是否展示
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  // id: undefined,
  wellId: undefined,
  wellName: undefined,
  wellType: undefined,
  wellCategory: undefined,
  oilField: undefined,
  oilFieldBlock: undefined,
  longitude: undefined,
  latitude: undefined,
  aimLayer: undefined,
  drillingDate: undefined,
  designWellde: undefined,
  drillingWellde: undefined,
  drillingLayer: undefined,
  welldeLithology: undefined,
  projectProfile: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  remark: undefined,
  state: undefined,
  country: undefined,
  province: undefined,
  city: undefined,
  county: undefined,
  addressId: undefined
})
const query = ref({
  accessToken: undefined,
  pageNum: 1,
  pageSize: 20
})
const total = ref()
const datas = ref([])
const scrollInterval = ref(null)
const setTime = () => {
  scrollInterval.value = setInterval(getTable, 10800000)
}
const stopScroll = () => {
  clearInterval(scrollInterval.value)
}
// 自定义验证函数
const validateLongitude = (rule, value, callback) => {
  if (value === null || value === '') {
    callback(new Error('经度是必填项'))
  } else if (value < -180 || value > 180) {
    callback(new Error('经度必须在 -180 到 180 之间'))
  } else {
    callback()
  }
}

const validateLatitude = (rule, value, callback) => {
  if (value === null || value === '') {
    callback(new Error('纬度是必填项'))
  } else if (value < -90 || value > 90) {
    callback(new Error('纬度必须在 -90 到 90 之间'))
  } else {
    callback()
  }
}

const validateDesignWellde = (rule, value, callback) => {
  if (value === '') {
    return callback(new Error(t('action.designDepthIsRequired')));
  } else if (!/^\d+(\.\d+)?$/.test(value)) {
    return callback(new Error(t('action.onlyNumbersAllowed')));
  } else {
    return callback();
  }
}


const ESICValue = ref({})
const handleCurrentChange = (val: User | undefined) => {
  stopScroll()
  ESICValue.value = val
  clicks.value = true
  formData.value.wellId = ESICValue.value.wellId
  formData.value.wellName = ESICValue.value.wellName
  dialogVisibleable.value = false
}
const formRules = reactive({
  longitude: [{ required: true, trigger: 'blur', validator: validateLongitude }],
  latitude: [{ required: true, trigger: 'blur', validator: validateLatitude }],



  wellName: [{ required: true, message: t('action.wellNameIsRequired'), trigger: 'blur' }],
  wellType: [{ required: true, message: t('action.wellTypeIsRequired'), trigger: 'blur' }],
  wellCategory: [{ required: true, message: t('action.wellCategoryIsRequired'), trigger: 'blur' }],
  oilField: [{ required: true, message: t('action.clientUnitIsRequired'), trigger: 'blur' }],
  oilFieldBlock: [{ required: true, message: t('action.blockIsRequired'), trigger: 'blur' }],


  // contactPerson: [{ required: true, message: t('action.contactNameIsRequired'), trigger: 'blur' }],
  contactPhone: [
    // { required: true, message: t('action.phoneNumberIsRequired'), trigger: 'blur' },
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: t('action.correctPhoneNumberRequired'),
      trigger: 'blur'
    }
  ],
  drillingDate: [{ required: true, message: t('action.drillingDateIsRequired'), trigger: 'blur' }],

  designWellde: [
    {
      required: true,
      message: t('action.designDepthIsRequired'),
      trigger: 'blur'
    },
    {
      validator: validateDesignWellde,
      trigger: 'blur'
    }
  ]
})

const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, wellCode?: string) => {
  // 调用地区接口
  clicks.value = false
  addressDataTree.value = await SiteApi.getAreatest()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SiteApi.getSite(wellCode)
      selectedAddress.value = [
        Number(formData.value.province),
        Number(formData.value.city),
        Number(formData.value.county)
      ]
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const getTable = async () => {
  try {
    loading.value = true
    const data = await SiteApi.getEiscAccessToken()
    query.value.accessToken = data
    const wellData = await SiteApi.getEiscWellList(query.value)
    datas.value = wellData.list
    total.value = wellData.total
  } catch {
  } finally {
    loading.value = false
  }
}

const getObtain = async () => {
  getTable()
  setTime()
  dialogVisibleable.value = true
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {



  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SiteVO
    if (formType.value === 'create') {
      await SiteApi.createSite(data)
      message.success(t('common.createSuccess'))
    } else {
      await SiteApi.updateSite(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    // id: undefined,
    wellId: undefined,
    wellName: undefined,
    wellType: undefined,
    wellCategory: undefined,
    oilField: undefined,
    oilFieldBlock: undefined,
    longitude: undefined,
    latitude: undefined,
    aimLayer: undefined,
    drillingDate: undefined,
    designWellde: undefined,
    drillingWellde: undefined,
    drillingLayer: undefined,
    welldeLithology: undefined,
    projectProfile: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    remark: undefined,
    state: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    county: undefined,
    addressId: undefined
  }
  selectedAddress.value = []
  formRef.value?.resetFields()
}

//所在位置地区树---------------------------------
// 树形结构
const addressDataTree = ref([])

const selectedAddress = ref([])
const addressChanges = (value) => {
  if (value.length === 3) {
    formData.value.province = value[0]
    formData.value.city = value[1]
    formData.value.county = value[2]
  } else {
    formData.value.province = ''
    formData.value.city = ''
    formData.value.county = ''
  }
}

//清空所在位置地区树级联选择器内容
const clearCascader = () => {
  addressDataTree.value = []
}
const handleDialogClose = () => {
  console.log('-----------------')
  dialogVisibleable.value = false
  if (scrollInterval.value) {
    clearInterval(scrollInterval.value)
    scrollInterval.value = null
  }
}
onUnmounted(() => {
  stopScroll()
})
</script>
